package leetcode;

public class MedianTwoSortedArrays {
	public double findMedianSortedArrays(int a[], int b[]) {
        if (a == null || b== null)
            return -1;
            
        if (a.length == 0 && b.length == 0)
            return -1;
        
        int mpos = (a.length + b.length - 1) / 2;
        
        int p = 0, ap = 0, bp = 0;
        int last = 0;
        while (p <= mpos){
            if (ap < a.length && bp<b.length){
                if (a[ap] <= b[bp]){
                    last = a[ap];
                    ++ap;                    
                }
                else{
                    last = b[bp];
                    ++bp;
                }
            } else if (ap <a.length){
                last = a[ap];
                ++ap;
            } else if (bp <b.length){
                last = b[bp];
                ++bp;
            } else{
                break;
            }
            
            ++p;
        }
        
        if ((a.length + b.length) %2 == 1)
            return last;
        
        if (ap >= a.length && bp >= b.length)
            return -1;
        
        int next;
        if (ap >= a.length){
                next = b[bp];
        } else if (bp >= b.length){
            next = a[ap];
        } else {
            next = Math.min(a[ap], b[bp]);
        }
        
        return (last + next) * 1.0d / 2;
    }
}
